from fastapi.responses import ORJSONResponse
from fastapi.routing import APIRouter
from logs.settings import loggers
from fastapi.responses import JSONResponse
from fastapi import *
from fastapi.responses import HTMLResponse
from views.login.func.model import *
from views.login.func.make_login import *
from datetime import *
import time
from datetime import datetime

router = APIRouter(
    prefix="/api",
    tags=["登录"],
    default_response_class=ORJSONResponse
)


@router.post("/login")
async def login(item: dict):
    username = item.get('username')
    password = item.get('password')
    user = users_collection.find_one({"username": username})

    if not user or not User(user["username"], password).verify_password(user["password_hash"]):
        return JSONResponse(status_code=401, content={"msg": "登录失败，请检查用户名密码"})

    access_token = create_access_token(
        {"username": user["username"], "time": time.time()*1000})

    # 创建Cookie
    response = JSONResponse(
        {"access_token": access_token, "token_type": "bearer", "msg": "登录成功"})
    expires = datetime.now(timezone.utc) + timedelta(days=1)  # 设置过期时间
    response.set_cookie(key="token", value=access_token,
                        expires=expires, secure=False, httponly=True)
    return response


@router.post("/register")
@login_check
async def register(request: Request, item: dict, level=1):
    username = item.get('username')
    password = item.get('password')
    level = str(item.get('level'))
    user = users_collection.find_one({"username": username})
    if user:
        return JSONResponse(status_code=400, content={"status": False, "msg": "Username already exists"})
    new_user = User(username, password, )
    user_dict = new_user.__dict__
    user_dict.update({"time": datetime.now(), "level": level})
    print(user_dict, item)
    users_collection.insert_one(user_dict)
    return {"msg": "User registered successfully"}


@router.post("/user/update")
@login_check
async def update(request: Request, item: dict, level=1):
    username = item.get('username')
    level = str(item.get('level'))
    password = item.get('password')
    oldpassword = item.get('oldpassword')
    field = {"username": username}
    user = users_collection.find_one(field)
    password_hash = user.get('password_hash')
    if user:
        oldpassword = User(username, oldpassword, ).password_hash
        new_user = User(username, password)
        if oldpassword == password_hash:
            user_dict = new_user.__dict__
            user_dict.update({"time": datetime.now(), "level": level})
            try:
                users_collection.update_one(field, {"$set": user_dict})
            except Exception as e:
                loggers.error(e)
            return JSONResponse(status_code=200, content={"status": True, "msg": "用户更新成功"})
        else:
            return JSONResponse(status_code=403, content={"status": False, "msg": "密码不一致"})
    # print(user_dict, item)
    # users_collection.insert_one(user_dict)
    return JSONResponse(status_code=403, content={"status": True, "msg": "用户更新失败"})


@router.post("/user/delete")
@login_check
async def delete(request: Request, item: dict, level=1):
    username = item.get('username')
    field = {"username": username}
    user = users_collection.find_one(field)
    if user:
        try:
            users_collection.delete_one(field)
        except Exception as e:
            loggers.error(e)
            return JSONResponse(status_code=403, content={"status": False, "msg": "删除失败"})
        return JSONResponse(status_code=200, content={"status": True, "msg": "删除成功"})

    # print(user_dict, item)
    # users_collection.insert_one(user_dict)
    return JSONResponse(status_code=403, content={"status": True, "msg": "删除失败"})


@router.get("/logout")
async def logout(request: Request):
    response = JSONResponse(content={"message": "Logout successful"})
    # 删除 cookie
    response.delete_cookie("token")
    return response


# 获取 Cookie 的路由
@router.get("/user")
async def user(request: Request):
    username = '9527'
    userlist = {}
    try:
        cookie_value = request.cookies.get("token")
        payload = jwt.decode(cookie_value, '9527', algorithms="HS256")
        username = payload.get('username')
        userlist = users_collection.find_one({"username": username})
    except Exception as e:
        return {"username": username, "status": "Logout", "level": userlist.get('level', 5)}

    return {"username": username, "status": "Login", "level": userlist.get('level', 5)}


@router.get("/user/list")
@login_check
async def get_user(request: Request, level=4):
    result_list = []
    try:
        result = users_collection.find({})
        for res in result:
            _id = res['_id']
            timenow = res.get('time')
            timenow = timenow.strftime("%Y-%m-%d %H:%M:%S") if time else time
            res['_id'] = str(_id)
            res['time'] = timenow
            result_list.append(res)
    except Exception as e:
        loggers.info(e)
        return JSONResponse(status_code=401, content={"data": result_list, "status": "error"})

    return JSONResponse(status_code=200, content={"data": result_list, "status": "success"})


@router.get("/test")
def logout():

    return {'status': False, 'data': None}


@router.post("/loginCode")
@login_check
async def loginCode(request: Request, item: dict, level=4):
    result = {}
    try:
        logindict = eval(item.get('logindict'))
        loginCode = get_loginCode(logindict)
        result = {"loginCode": loginCode}
    except Exception as e:
        loggers.info(e)
        return JSONResponse(status_code=200, content={"data": result, "status": "error"})

    return JSONResponse(status_code=200, content={"data": result, "status": "success"})
